// 游戏渲染和交互逻辑
class GameRenderer {
    constructor() {
        // 获取DOM元素
        this.gameCanvas = document.getElementById('gameCanvas');
        this.nextCanvas = document.getElementById('nextCanvas');
        this.gameCtx = this.gameCanvas.getContext('2d');
        this.nextCtx = this.nextCanvas.getContext('2d');
        
        // 获取分数和按钮元素
        this.scoreElement = document.getElementById('score');
        this.linesElement = document.getElementById('lines');
        this.levelElement = document.getElementById('level');
        this.startBtn = document.getElementById('startBtn');
        this.pauseBtn = document.getElementById('pauseBtn');
        this.resetBtn = document.getElementById('resetBtn');
        this.restartBtn = document.getElementById('restartBtn');
        this.gameOverElement = document.getElementById('gameOver');
        this.finalScoreElement = document.getElementById('finalScore');
        
        // 创建游戏实例
        this.tetris = new Tetris();
        this.animationId = null;
        this.isGameRunning = false;
        
        // 初始化事件监听
        this.initEventListeners();
        
        // 初始渲染
        this.render();
    }
    
    // 初始化事件监听
    initEventListeners() {
        // 按钮事件
        this.startBtn.addEventListener('click', () => this.startGame());
        this.pauseBtn.addEventListener('click', () => this.togglePause());
        this.resetBtn.addEventListener('click', () => this.resetGame());
        this.restartBtn.addEventListener('click', () => this.restartGame());
        
        // 键盘事件
        document.addEventListener('keydown', (event) => this.handleKeyPress(event));
    }
    
    // 处理键盘输入
    handleKeyPress(event) {
        // 防止默认行为
        if (['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', ' '].includes(event.key)) {
            event.preventDefault();
        }
        
        switch (event.key) {
            case 'ArrowLeft':
                this.tetris.move(-1);
                break;
            case 'ArrowRight':
                this.tetris.move(1);
                break;
            case 'ArrowDown':
                this.tetris.drop();
                // 按下下移键给予少量分数奖励
                if (!this.tetris.gameOver && !this.tetris.paused) {
                    this.tetris.score += 1;
                    this.updateScoreDisplay();
                }
                break;
            case 'ArrowUp':
                this.tetris.rotateCurrent();
                break;
            case ' ':
                this.tetris.hardDrop();
                // 硬下落奖励分数
                if (!this.tetris.gameOver && !this.tetris.paused) {
                    const dropDistance = this.calculateDropDistance();
                    this.tetris.score += dropDistance * 2;
                    this.updateScoreDisplay();
                }
                break;
            case 'p':
            case 'P':
                this.togglePause();
                break;
        }
    }
    
    // 计算方块下落距离（用于硬下落分数计算）
    calculateDropDistance() {
        const { currentPiece } = this.tetris;
        let dropDistance = 0;
        
        while (this.tetris.isValidMove(currentPiece, 0, dropDistance + 1)) {
            dropDistance++;
        }
        
        return dropDistance;
    }
    
    // 开始游戏
    startGame() {
        if (!this.isGameRunning) {
            this.isGameRunning = true;
            this.updateButtonStates();
            this.gameLoop();
        }
    }
    
    // 暂停/继续游戏
    togglePause() {
        const isPaused = this.tetris.togglePause();
        this.updateButtonStates();
        
        // 如果从暂停状态恢复，继续游戏循环
        if (!isPaused && this.isGameRunning) {
            this.lastTime = 0;
            this.gameLoop();
        }
    }
    
    // 重置游戏
    resetGame() {
        this.stopGame();
        this.tetris.reset();
        this.updateScoreDisplay();
        this.render();
        this.updateButtonStates();
    }
    
    // 重新开始游戏（游戏结束后）
    restartGame() {
        this.gameOverElement.style.display = 'none';
        this.resetGame();
        this.startGame();
    }
    
    // 停止游戏
    stopGame() {
        if (this.animationId) {
            cancelAnimationFrame(this.animationId);
            this.animationId = null;
        }
        this.isGameRunning = false;
    }
    
    // 更新按钮状态
    updateButtonStates() {
        this.startBtn.disabled = this.isGameRunning;
        this.pauseBtn.disabled = !this.isGameRunning;
        this.resetBtn.disabled = !this.isGameRunning;
        
        // 更新暂停按钮文本
        this.pauseBtn.textContent = this.tetris.paused ? '继续' : '暂停';
    }
    
    // 更新分数显示
    updateScoreDisplay() {
        this.scoreElement.textContent = this.tetris.score;
        this.linesElement.textContent = this.tetris.lines;
        this.levelElement.textContent = this.tetris.level;
    }
    
    // 游戏主循环
    gameLoop(time = 0) {
        if (this.tetris.gameOver) {
            this.handleGameOver();
            return;
        }
        
        if (this.tetris.paused) {
            return;
        }
        
        // 更新游戏状态
        this.tetris.update(time);
        
        // 更新分数显示
        this.updateScoreDisplay();
        
        // 渲染游戏
        this.render();
        
        // 继续游戏循环
        this.animationId = requestAnimationFrame((time) => this.gameLoop(time));
    }
    
    // 处理游戏结束
    handleGameOver() {
        this.stopGame();
        this.finalScoreElement.textContent = this.tetris.score;
        this.gameOverElement.style.display = 'flex';
        this.updateButtonStates();
    }
    
    // 渲染游戏
    render() {
        // 渲染游戏区域
        this.renderGameBoard();
        // 渲染下一个方块预览
        this.renderNextPiece();
    }
    
    // 渲染游戏板
    renderGameBoard() {
        const { board, currentPiece, colors, BLOCK_SIZE } = this.tetris.getState();
        
        // 清空画布
        this.gameCtx.clearRect(0, 0, this.gameCanvas.width, this.gameCanvas.height);
        
        // 渲染已落下的方块
        for (let y = 0; y < board.length; y++) {
            for (let x = 0; x < board[y].length; x++) {
                if (board[y][x] !== 0) {
                    this.drawBlock(x * BLOCK_SIZE, y * BLOCK_SIZE, colors[board[y][x]], BLOCK_SIZE);
                }
            }
        }
        
        // 渲染当前方块
        if (currentPiece) {
            const { shape, x, y, type } = currentPiece;
            
            for (let py = 0; py < shape.length; py++) {
                for (let px = 0; px < shape[py].length; px++) {
                    if (shape[py][px] !== 0) {
                        const drawX = (x + px) * BLOCK_SIZE;
                        const drawY = (y + py) * BLOCK_SIZE;
                        
                        // 只渲染在可见区域内的方块
                        if (drawY >= 0) {
                            this.drawBlock(drawX, drawY, colors[type], BLOCK_SIZE);
                        }
                    }
                }
            }
        }
        
        // 渲染网格线
        this.renderGrid();
        
        // 如果游戏暂停，显示暂停文字
        if (this.tetris.paused) {
            this.renderPauseText();
        }
    }
    
    // 渲染下一个方块预览
    renderNextPiece() {
        const { nextPiece, colors } = this.tetris.getState();
        
        // 清空画布
        this.nextCtx.clearRect(0, 0, this.nextCanvas.width, this.nextCanvas.height);
        
        if (nextPiece) {
            const { shape, type } = nextPiece;
            const blockSize = 20; // 预览区域的方块大小
            
            // 计算居中位置
            const pieceWidth = shape[0].length * blockSize;
            const pieceHeight = shape.length * blockSize;
            const offsetX = (this.nextCanvas.width - pieceWidth) / 2;
            const offsetY = (this.nextCanvas.height - pieceHeight) / 2;
            
            // 渲染下一个方块
            for (let y = 0; y < shape.length; y++) {
                for (let x = 0; x < shape[y].length; x++) {
                    if (shape[y][x] !== 0) {
                        const drawX = offsetX + x * blockSize;
                        const drawY = offsetY + y * blockSize;
                        this.drawBlock(drawX, drawY, colors[type], blockSize);
                    }
                }
            }
        }
    }
    
    // 绘制单个方块
    drawBlock(x, y, color, size) {
        // 绘制方块主体
        this.gameCtx.fillStyle = color;
        this.gameCtx.fillRect(x, y, size, size);
        
        // 绘制方块边框
        this.gameCtx.strokeStyle = '#333';
        this.gameCtx.lineWidth = 1;
        this.gameCtx.strokeRect(x, y, size, size);
        
        // 绘制高光效果
        this.gameCtx.fillStyle = 'rgba(255, 255, 255, 0.3)';
        this.gameCtx.fillRect(x + 2, y + 2, size - 4, size / 2 - 2);
        
        // 绘制阴影效果
        this.gameCtx.fillStyle = 'rgba(0, 0, 0, 0.2)';
        this.gameCtx.fillRect(x + 2, y + size / 2, size - 4, size / 2 - 2);
    }
    
    // 渲染网格线
    renderGrid() {
        const { COLUMNS, ROWS, BLOCK_SIZE } = this.tetris.getState();
        
        this.gameCtx.strokeStyle = '#e0e0e0';
        this.gameCtx.lineWidth = 0.5;
        
        // 绘制垂直线
        for (let x = 0; x <= COLUMNS; x++) {
            this.gameCtx.beginPath();
            this.gameCtx.moveTo(x * BLOCK_SIZE, 0);
            this.gameCtx.lineTo(x * BLOCK_SIZE, ROWS * BLOCK_SIZE);
            this.gameCtx.stroke();
        }
        
        // 绘制水平线
        for (let y = 0; y <= ROWS; y++) {
            this.gameCtx.beginPath();
            this.gameCtx.moveTo(0, y * BLOCK_SIZE);
            this.gameCtx.lineTo(COLUMNS * BLOCK_SIZE, y * BLOCK_SIZE);
            this.gameCtx.stroke();
        }
    }
    
    // 渲染暂停文字
    renderPauseText() {
        this.gameCtx.fillStyle = 'rgba(0, 0, 0, 0.5)';
        this.gameCtx.fillRect(0, 0, this.gameCanvas.width, this.gameCanvas.height);
        
        this.gameCtx.fillStyle = 'white';
        this.gameCtx.font = 'bold 30px Arial';
        this.gameCtx.textAlign = 'center';
        this.gameCtx.fillText('游戏暂停', this.gameCanvas.width / 2, this.gameCanvas.height / 2);
    }
}

// 当页面加载完成后初始化游戏
window.addEventListener('load', () => {
    const game = new GameRenderer();
});